package com.feilong.edgeAI.vm;

import static com.aiibt.common.util.Constant.BASE_DOWN_URL;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.lifecycle.MutableLiveData;

import com.aiibt.common.bean.AppVersion;
import com.aiibt.common.bean.XxzVersion;
import com.aiibt.common.core.DataCall;
import com.aiibt.common.core.WDViewModel;
import com.aiibt.common.core.exception.ApiException;
import com.aiibt.common.util.Constant;
import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.feilong.edgeAI.R;
import com.feilong.edgeAI.model.PlayTTs;
import com.feilong.edgeAI.model.StartVoice;
import com.feilong.edgeAI.request.IMainRequest;
import com.feilong.edgeAI.ui.SettingActivity;
import com.feilong.edgeAI.update.ApkUpdateService;
import com.feilong.edgeAI.update.StorageUtils;
import com.feilong.edgeAI.update.XxzUpdateService;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import java.io.File;


public class MainViewModel extends WDViewModel<IMainRequest> {
    public MutableLiveData<AppVersion> result = new MutableLiveData<>();
    private static final String TAG = "MainViewModel";
    @Override
    protected void create() {
        super.create();
    }

    public void goSetting() {
        intentByRouter(Constant.ACTIVITY_URL_SETTING);
    }
    public void startVoice() {
        EventBus.getDefault().post(new StartVoice());
    }

    /**
     * 正式版
     * @param context
     * @param isClick
     */
    public void requestAppLastVersion(Context context, boolean isClick) {
        request(iRequest.appLastVersion(), new DataCall<AppVersion>() {
            @Override
            public void success(AppVersion data) {
                handleAppUpdate(context,data,isClick,false,false);
            }

            @Override
            public void fail(ApiException data) {
                Log.d("MainViewModel", "ApiException: "+data);
            }
        });
    }

    /**
     * 测试版
     * @param context
     * @param isClick
     */
    public void requestAppLastVersionTest(Context context, boolean isClick,boolean updateXxz) {
        request(iRequest.appLastVersionTest(0), new DataCall<AppVersion>() {
            @Override
            public void success(AppVersion data) {
                handleAppUpdate(context,data,isClick,updateXxz,true);
            }

            @Override
            public void fail(ApiException data) {
                ToastUtils.showLong(data.getCode()+data.getDisplayMessage());
                Log.d("MainViewModel", "ApiException: "+data);
            }
        });
    }

    /**
     * 更新理解正式版
     * @param context
     * @param isClick
     */
    public void requestXXZLastVersion(Context context, boolean isClick) {
        request(iRequest.xxzLastVersion(), new DataCall<AppVersion>() {
            @Override
            public void success(AppVersion data) {
                Log.d(TAG, "success111: "+data);
                result.setValue(data);
                handleXxzUpdate(context, data);
            }

            @Override
            public void fail(ApiException data) {
//                ToastUtils.showLong(data.getCode()+data.getDisplayMessage());
                Log.d("MainViewModel", "ApiException: "+data);
            }
        });
    }
    /**
     * 更新理解测试版
     * @param context
     * @param
     */
    public void requestXXZLastVersionTest(Context context) {
        request(iRequest.xxzLastVersion(0), new DataCall<AppVersion>() {
            @Override
            public void success(AppVersion data) {
                result.setValue(data);
                handleXxzUpdate(context, data);
            }

            @Override
            public void fail(ApiException data) {
                Log.d("MainViewModel", "ApiException: "+data);
            }
        });
    }
//    private void handleAppUpdate(Context context, AppVersion data,boolean updateXxz,boolean isClick) {

    private static final String OTHER = "other_version";
    private static final String FEILONG = "mt6771_version";
    /**
     * 查询app是否有新版本（app先更新，再更新理解xxz）
     * @param context
     * @param data
     * @param isClick
     * @param updateXxz//如果app没有新版本，updateXxz=true，就检查更新理解xxz
     */
    private void handleAppUpdate(Context context, AppVersion data,boolean isClick,boolean updateXxz,boolean test) {
        if(null==data)return;
        result.setValue(data);
        AppVersion appVersion = data;
        int apkCode = Integer.valueOf(appVersion.getVersionCode());
        try {
            int versionCode = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0).versionCode;
            if (apkCode > versionCode) {//app先更新
                String apkUrl = BASE_DOWN_URL+appVersion.getPath();
                if("20226399".equals(Build.MODEL)&&"mt6771".equals(Build.HARDWARE)){//anica正式版手机
                    apkUrl=apkUrl.replaceAll(OTHER,FEILONG);
                }else{//其他手机
                    apkUrl=apkUrl.replaceAll(FEILONG,OTHER);
                }
                showDownLoad(context,appVersion.getDesc(),apkUrl);
            }else{
                if(updateXxz){
                    if(test){
                        requestXXZLastVersionTest(context);//更新测试版理解
                    }else{
                        requestXXZLastVersion(context,false);//更新正式版理解
                    }
                }
                if(isClick&&!updateXxz){
                    Toast.makeText(context, R.string.lastest_version,Toast.LENGTH_LONG).show();
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }
    private void handleXxzUpdate(Context context, AppVersion data){
        if(null == data){
            return;
        }
        AppVersion appVersion = data;

        String onlineCode = appVersion.getVersionCode();
        String code = SPUtils.getInstance().getString(SettingActivity.FEILONG_VERSION_CODE, "");
        try {
            if (!onlineCode.equals(code)) {
                String xxzUrl = BASE_DOWN_URL+appVersion.getPath();

                Intent intent = new Intent(context, XxzUpdateService.class);
                intent.putExtra(XxzUpdateService.XXZ_DOWNLOAD_URL, xxzUrl);
                ToastUtils.showShort(R.string.start_update_xxz);
                EventBus.getDefault().post(new PlayTTs(context.getString(R.string.start_update_xxz)));
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    context.startForegroundService(intent);
                } else {
                    context.startService(intent);
                }
            }else{
                EventBus.getDefault().post(new PlayTTs(context.getString(R.string.current_new_version)));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void showDownLoad(Context context, String msg, final String url) {

        LayoutInflater layoutInflater = LayoutInflater.from(context);
        View v = layoutInflater.inflate(R.layout.update_dialog, null);
        final AlertDialog dialog = new AlertDialog.Builder(context, AlertDialog.THEME_HOLO_LIGHT)
                .setView(v).create();
        TextView contentTextView = v.findViewById(R.id.update_content);
        contentTextView.setText(msg);
        v.findViewById(R.id.update_confim_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, ApkUpdateService.class);
                intent.putExtra(ApkUpdateService.APK_DOWNLOAD_URL, url);

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    context.startForegroundService(intent);
                } else {
                    context.startService(intent);
                }
                dialog.dismiss();
            }
        });
        v.findViewById(R.id.update_confim_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        try {

            dialog.show();
            dialog.setView(v, 0, 0, 0, 0);
            dialog.setCancelable(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
